import { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { View, Text, Image, ScrollView } from '@tarojs/components'
import { connect } from 'react-redux'
import { AtModal, AtTextarea } from 'taro-ui'
import { getGoodsMatchList, feedbackCreate } from '@/api/assistant'
import { staticUrl, accAdd, accMul } from '@/utils'
import classnames from 'classnames'

import './index.scss'
interface State {
  queryParams: object,
  checkedList: object,
  manualShow: boolean,
  isOpened: boolean,
  isFeedbackOpened: boolean,
  feedback: string,
  list: any,
  categoryId: any,
  carInfo: any
}

const recommend_s_1 = staticUrl('/img/assistant/recommend_1.png')
const recommend_s_2 = staticUrl('/img/assistant/recommend_2.png')
const recommend_s_3 = staticUrl('/img/assistant/recommend_3.png')
const recommend_s_4 = staticUrl('/img/assistant/recommend_4.png')

@connect<any>(({ user, car }) => ({ user, car }))
export default class Index extends Component {
  $instance = getCurrentInstance();
  constructor (props) {
    super(props)
    this.state = {
      queryParams: {},
      checkedList: [1],
      manualShow: false,
      isOpened: false,
      isFeedbackOpened: false,
      feedback: '',
      list: [],
      categoryId: 0,
      carInfo: {
        paramInfo: null
      }
    }
  }

  state: State


  UNSAFE_componentWillMount() {
  }
  componentDidMount() {

  }
  UNSAFE_componentWillReceiveProps(nextProps, nextContext) { }
  componentDidShow() {
    let { jekunModelCode, carLicense, projectId, goodsId, categoryId } = this.$instance.router.params
    let carInfo = Taro.getStorageSync('MAINTAIN_SCHEME_CAR') || {}
    this.setState({ queryParams: { jekunModelCode, carLicense, projectId, goodsId }, categoryId, carInfo }, () => {
      this.getList()
    })
  }
  private PER_PAGE: number = 20
  private MAX_PAGE: number = 1
  private curPage: number = 1
  private isPageEnd: boolean = false
  getList(mode: string = 'init') {
    let { queryParams, carInfo } = this.state
    if (mode === 'init') {
      this.curPage = 1
      this.isPageEnd = false
    } else {
      this.curPage++
      this.isPageEnd = this.curPage > this.MAX_PAGE
    }
    if (this.isPageEnd) return
    Taro.showLoading({ title: '加载中' })
    getGoodsMatchList({
      ...queryParams,
      curPage: this.curPage
    }).then(res => {
      const data = res.data.data.goodsItems
      Taro.hideLoading()
      carInfo.paramInfo = res.data.data.paramInfo
      if (mode === 'init') {
        this.MAX_PAGE = Number(res.header['x-pagination-page-count']) || Number(res.header['X-Pagination-Page-Count'])
        this.setState({
          list: data
        })
      } else {
        const { list } = this.state
        this.setState({
          list: [...list, ...data],
          carInfo
        })
      }
    }).catch(e => {
      Taro.hideLoading()
    })
  }

  // 滚动加载
  scrollLoad(e) {
    this.getList('add')
  }
  handleChangeGoods = (goods) => {
    let { queryParams, categoryId } = this.state
    let MAINTAIN_SCHEME_GOODS = Taro.getStorageSync('MAINTAIN_SCHEME_GOODS')
    if (MAINTAIN_SCHEME_GOODS) {
      let categoryIndex = MAINTAIN_SCHEME_GOODS.findIndex(v => v.categoryId == categoryId)
      let projectItemsIndex = MAINTAIN_SCHEME_GOODS[categoryIndex].projectItems.findIndex(v => v.projectId = queryParams.projectId)
      let goodsIndex = MAINTAIN_SCHEME_GOODS[categoryIndex].projectItems[projectItemsIndex].goodsMatchData.goodsItems.findIndex(v => v.goodsId == queryParams.goodsId)
      if (!goods.number) {
        goods.number = MAINTAIN_SCHEME_GOODS[categoryIndex].projectItems[projectItemsIndex].goodsMatchData.goodsItems[goodsIndex].number
      }
      MAINTAIN_SCHEME_GOODS[categoryIndex].projectItems[projectItemsIndex].goodsMatchData.goodsItems[goodsIndex] = goods
      Taro.setStorageSync("MAINTAIN_SCHEME_GOODS", MAINTAIN_SCHEME_GOODS)
      console.log(MAINTAIN_SCHEME_GOODS)
      Taro.navigateBack({
        delta: 1
      })
    }
  }

  setFeedback(v) {
    this.setState({
      feedback: v
    })
  }


  changeDialog = (key, value) => {
    this.setState({
      [key]: value
    })
  }

  submitFeedback = () => {
    let { feedback } = this.state
    if (!feedback) {
      Taro.showToast({ title: '请填写反馈内容', icon: 'none' })
      return
    }
    feedbackCreate({
      type: 4,
      content: feedback
    }).then(res => {
      Taro.showToast({ title: '反馈成功' })
      this.changeDialog('isFeedbackOpened', false)
    })
  }

  render() {
    let { isOpened, isFeedbackOpened, list, carInfo } = this.state;


    return (

      <View className="assistant-exchange" >
        <View className='car-info-box'>
          <View className='car-info'>
            <Image className='car-img' src={carInfo.brandLogo} mode='aspectFit'></Image>
            <View className='car-right'>
              <View className='car-license'>{carInfo.carLicense} <Text className='right-allow'></Text></View>
              <View className='car-name'>{carInfo.carModelShortLabel}</View>
              {/* 1:燃油,2:纯电动,3:油电混合 */}
              <View className={classnames('car-type', {
                'car-type1': carInfo.carFuelType == 1,
                'car-type2': carInfo.carFuelType == 2,
                'car-type3': carInfo.carFuelType == 3,
              })}>{carInfo.carFuelTypeLabel}</View>
            </View>
          </View>
          <View className='car-params'>
            <View className='r-line'>
              <View className='line-item'>参考用量：{carInfo.paramInfo && carInfo.paramInfo.referCapacity || '--'}</View>
              <View className='line-item'>机油类型：{carInfo.paramInfo && carInfo.paramInfo.oilTypeLabel || '--'}</View>
            </View>
            <View className='r-line'>
              <View className='line-item'>基础油类型：{carInfo.paramInfo && carInfo.paramInfo.baseOilTypeLabel || '--'}</View>
              <View className='line-item item-more' onClick={() => this.changeDialog('isOpened', true)}><Text className='t'>更多</Text> <Text className='right-allow'></Text> </View>
            </View>
          </View>
        </View>
        <View className='car-tips'>
          <Text className='tips-ico'></Text>
          为您优先展示适配的机油，请根据开车环境和实际车况选择！
        </View>

        <ScrollView scrollY lowerThreshold={150} onScrollToLower={(e) => this.scrollLoad(e)}>
          <View className='product-list'>
            {
              list.map(goods => {
                return <View className='product-item'>
                  <View className='product-item__l'>
                    <Image className='pic-img' src={goods.goodsThumbnail}></Image>
                    {
                      goods.recommendType === 1 ? <Image className='recommand-tag' src={recommend_s_1}></Image> :
                        goods.recommendType === 2 ? <Image className='recommand-tag' src={recommend_s_2}></Image> :
                          goods.recommendType === 3 ? <Image className='recommand-tag' src={recommend_s_3}></Image> :
                            goods.recommendType === 4 ? <Image className='recommand-tag' src={recommend_s_4}></Image> : null
                    }
                  </View>
                  <View className='pro-info'>
                    <View className='pro-name'>{goods.goodsName}</View>
                    <View className='pro-tag'>
                      {
                        goods.goodsTags && goods.goodsTags.map(tag => {
                          return <View className='tag-box'>{tag}</View>
                        })
                      }
                    </View>
                    <View className='pro-stock'>库存：{goods.stockCount}</View>
                    <View className='pro-price'>
                      <View className='pp_l'>￥<Text className='pp_l_t2'>{goods.salePrice}</Text>起</View>
                      {
                        goods.isCurSelected ? <View className='pp_r'>当前选择</View> : <View className='pp_r pp_change' onClick={() => this.handleChangeGoods(goods)}>更换</View>
                      }
                    </View>
                  </View>
                </View>
              })
            }
            {
              console.log('isPageEnd', this.isPageEnd)
              // this.isPageEnd ? <View className="page-base">已经到底了~</View> : null
            }
          </View>
        </ScrollView >


        <AtModal isOpened={isOpened} closeOnClickOverlay={false}>
          <View className='error-wrap'>
            <View className='error-title'>{carInfo.carModelShortLabel} · 适配小贴士</View>
            <View className='error-content'>
              <View className='error-content__l'>
                <View className='error-line'>参考用量：{carInfo.paramInfo && carInfo.paramInfo.referCapacity || '--'}</View>
                <View className='error-line'>机油类型：{carInfo.paramInfo && carInfo.paramInfo.oilTypeLabel || '--'}</View>
                <View className='error-line'>基础油类型：{carInfo.paramInfo && carInfo.paramInfo.baseOilTypeLabel || '--'}</View>
                <View className='error-line'>原厂粘度：{carInfo.paramInfo && carInfo.paramInfo.viscosity || '--'}</View>
                <View className='error-line'>油品级别：{carInfo.paramInfo && carInfo.paramInfo.oilLevel || '--'}</View>
                <View className='error-line'>备注：{carInfo.paramInfo && carInfo.paramInfo.remark || '--'}</View>
              </View>
              <View className='error-content__r' onClick={() => this.changeDialog('isFeedbackOpened', true)}>反馈错误</View>
            </View>
            <View className='error-btn' onClick={() => this.changeDialog('isOpened', false)}>知道了</View>
          </View>
        </AtModal>

        <AtModal isOpened={isFeedbackOpened} onClose={() => this.changeDialog('isFeedbackOpened', false)}>
          <View className='error-wrap'>
            <View className='error-title'>反馈错误</View>
            <View className='error-content'>
              <AtTextarea
                className='textarea'
                value={this.state.feedback}
                onChange={this.setFeedback.bind(this)}
                maxLength={200}
                height={290}
                placeholder='你的问题是...'
              />
            </View>
            <View className='error-btn' onClick={this.submitFeedback}>提交反馈</View>
          </View>
        </AtModal>
      </View >
    )
  }
}
